<?php

namespace backend\modules\goods\controllers;

use backend\modules\base\controllers\BaseController;
use backend\modules\comLib\ImgLib;
use backend\modules\goods\models\Attribute;
use backend\modules\goods\models\Attrvalue;
use backend\modules\goods\models\AttrvalueGoods;
use backend\modules\goods\models\GoodsDescImages;
use backend\modules\goods\models\GoodsGallImages;
use Yii;
use backend\modules\goods\models\Goods;
use backend\modules\goods\models\search\GoodsSearch;
use yii\base\Exception;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * GoodsController implements the CRUD actions for Goods model.
 */
class GoodsController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['attriall','updateimagesdeal','updatepage','deleteimage','logout', 'index','sort','create','view','update','delete','descupload','gallupload','sortdesc'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Goods models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new GoodsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Goods model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Goods model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Goods();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->cache->delete(('goodsAttributeInfo'));
            return $this->redirect(['update', 'id' => $model->goods_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Goods model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        //选中显示页面
        $FormPage = isset($_GET['whiceForm'])?$_GET['whiceForm']:'FormPage01';

        $beginTransaction = Yii::$app->db->beginTransaction();
        $postData = Yii::$app->request->post();
        try {
            if ($model->load($postData) ) {
                if($model->save()){

                    //没选择属性分类
                    if($model->attr_cat_id){
                        $Attrs = isset($postData['Attrs'])?$postData['Attrs']:'';
                        //修改属性
                        AttrvalueGoods::deleteAll(['goods_id'=>$id]);
                        $attrText = '';
                        //是否选中值
                        if($Attrs) {
                            if(Goods::isReloadAttr($id,$model->attr_cat_id,$Attrs)){
                                throw new Exception('同一属性分类不可以选中同一属性值组合！');
                            }
                            $attrvalueStr = implode('',$Attrs);
                            foreach($Attrs as $k=>$v){
                                $attribute=Attribute::findOne($k);
                                if($attribute){
                                    $attrvalue=Attrvalue::findOne($v);
                                    $attrvalueGoods = new AttrvalueGoods();
                                    $attrvalueGoods->attr_id = $attribute->attr_id;
                                    $attrvalueGoods->attr_name = $attribute->attr_name;
                                    $attrvalueGoods->attr_value_id = $attrvalue->attr_value_id;
                                    $attrvalueGoods->attr_value_name = $attrvalue->attr_value_name;
                                    $attrvalueGoods->goods_id = $id;
                                    $attrvalueGoods->attr_cat_id = $model->attr_cat_id;
                                    $attrvalueGoods->attr_value_string =$attrvalueStr;
                                    $attrText .= $attribute->attr_name.":".$attrvalue->attr_value_name."-----";
                                    if(!$attrvalueGoods->save()){
                                        throw new Exception(json_encode($attrvalueGoods->errors));
                                    }
                                }
                            }
                        }
                        //是否选中值END
                        $model->attrText = rtrim($attrText,'-----');
                        $model->save();
                    }
                    $beginTransaction->commit();
                    return $this->redirect(['update', 'id' => $model->goods_id]);
                }
            } else {
                //商品处理管理页面显示数据
                $GoodsGallImages = GoodsGallImages::find()->where(['goods_id'=>$id])->orderBy(['sort_number'=>SORT_ASC])->asArray()->all();
                $GoodsDescImages = GoodsDescImages::find()->where(['goods_id'=>$id])->orderBy(['sort_number'=>SORT_ASC])->asArray()->all();

                return $this->render('update', [
                    'model' => $model,
                    'GoodsGallImages'=>$GoodsGallImages,
                    'GoodsDescImages'=>$GoodsDescImages,
                    'FormPage'=>$FormPage
                ]);
            }
        } catch(Exception $e){
            $beginTransaction->rollBack();
            print_r($e->getMessage());exit;
        }

    }

    /**
     * Deletes an existing Goods model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Goods model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Goods the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Goods::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * 商品详情图片上传
     */
    public function actionDescupload()
    {
        $time = time();
        if($_FILES==null){
            echo  json_encode([]);exit;
        }
        $postData = Yii::$app->request->post();
        $baseUrl = Yii::$app->basePath;
        $goods_id = $postData['goods_id'];

        $webUrlBaseOnApp= '/web/images/goods/DescImages/'.$goods_id.'/';
        $baseImages = $baseUrl.$webUrlBaseOnApp;
        is_dir($baseImages) OR mkdir($baseImages, 0777, true);

        $sourceImg = $_FILES['Goods']['tmp_name']['descImages'][0];
        $imageName = time().'-'.rand(10,1000).'.png';

        $objImage = $baseImages.$imageName;

        if(move_uploaded_file($sourceImg,$objImage)){
            $goods_desc_image  = $webUrlBaseOnApp.$imageName;
            $GoodsDescImages = new GoodsDescImages();
            $GoodsDescImages->goods_desc_image = $goods_desc_image;
            $GoodsDescImages->goods_id = $goods_id;
            $GoodsDescImages->created_at = $time;
            if($GoodsDescImages->save()) {
                echo  json_encode([]);exit;
            }
            print_r($GoodsDescImages->errors);
        }else{
            echo json_encode("Failed!");
        }
    }

    /**
     * 商品主图图片上传
     * @throws \yii\db\Exception
     */
    public function actionGallupload()
    {
        if($_FILES==null){
            echo  json_encode([]);exit;
        }
        $postData = Yii::$app->request->post();
        $baseUrl = Yii::$app->basePath;
        $goods_id = $postData['goods_id'];

        $webUrlBaseOnApp= '/web/images/goods/GallImages/'.$goods_id.'/';
        $baseImages = $baseUrl.$webUrlBaseOnApp;
        is_dir($baseImages) OR mkdir($baseImages, 0777, true);

        $sourceImg = $_FILES['Goods']['tmp_name']['gallImages'][0];
        $imageName = time().'-'.rand(10,1000).'.png';

        $objImage = $baseImages.$imageName;

        //
        $connection = Yii::$app->db;
        $transaction = $connection->beginTransaction();
        try{
            if(move_uploaded_file($sourceImg,$objImage)){
                $goods_gall_image  = $webUrlBaseOnApp.$imageName;
                $GoodsGallImages = new GoodsGallImages();
                $GoodsGallImages->goods_gall_image = $goods_gall_image;
                $GoodsGallImages->goods_id = $goods_id;
                if(!$GoodsGallImages->save()) {
                    throw new Exception(json_encode($GoodsGallImages->errors));
                }
//                Goods::SortingImages($goods_id);
                $transaction->commit();
                return json_encode(array(true,[]));
            }else{
                throw new Exception(json_encode('文件上传失败！'));
            }
        }catch (Exception $e){
             $transaction->rollBack();
             print_r($e->getMessage());exit;
        }

    }

    /**
     * 移动排序图片
     * @return string
     * @throws \yii\db\Exception
     */
    public function actionSort()
    {
        $postData = Yii::$app->request->getRawBody();
        $dataArray = json_decode($postData,true);

        //
        $connection = Yii::$app->db;
        $transaction = $connection->beginTransaction();
        try {
            foreach($dataArray as $key=>$val) {
                if($val['classId']=='GallImages'){
                    $GoodsGallImages =   GoodsGallImages::findOne([$val['id']]);
                    $GoodsGallImages->sort_number = $val['sort_number'];
                    if(!$GoodsGallImages->save()){
                        throw new Exception($GoodsGallImages->errors);
                    }
                    if($val['sort_number']==0){
                        $goods_id = GoodsGallImages::findOne(['goods_gall_images_id'=>$dataArray[0]['id']])->goods_id;
                        $goods = Goods::findOne($goods_id);
                        $goods->goods_image = GoodsGallImages::findOne(['goods_gall_images_id'=>$dataArray[0]['id']])->goods_gall_image;

                        $image = new ImgLib();
                        //源图路径
                        $src_path = Yii::$app->basePath.$goods->goods_image;
                        $smpath = $image->thumb($src_path,100,100);

                        $str = trim(strrchr($goods->goods_image, '/'),'/');
                        $str = str_replace($str, '', $goods->goods_image);

                        $goods->thumb_img = $str. 'sm_'.$smpath;

                        if(!$goods->save()){
                            throw new Exception($goods->errors);
                        }
                    }
                } elseif($val['classId']=='DescImages'){
                    $GoodsDescImages =   GoodsDescImages::findOne([$val['id']]);
                    $GoodsDescImages->sort_number = $val['sort_number'];
                    if(!$GoodsDescImages->save()){
                        throw new Exception($GoodsDescImages->errors);
                    }
                }
            }

            $transaction->commit();
            return json_encode([true,[]]);
        } catch (Exception $e) {
            $transaction->rollBack();
            return json_encode([$e->getMessage()]);
        }
    }

    /**
     * 图片删除
     *
     * @param $id
     * @return \yii\web\Response
     * @throws \Exception
     * @throws \Throwable
     */
    public function  actionDeleteimage($id)
    {
        $imagesType = isset($_GET['imagesType'])?$_GET['imagesType']:'GallImages';
        if($imagesType=='GallImages'){
            if($id){
                $GoodsGallImages = GoodsGallImages::findOne($id);
                $goods_id  = $GoodsGallImages->goods_id;
                //
                $connection = Yii::$app->db;
                $transaction = $connection->beginTransaction();
                try{

                    $GoodsGallImages->delete();
                    Goods::SortingImages($goods_id);
                    if (!@unlink(Yii::$app->basePath.$GoodsGallImages->goods_gall_image))
                    {
                        throw new Exception('图片文件删除失败');
                    }
                    $transaction->commit();
                    return $this->redirect(['updatepage','id'=>$goods_id,'whiceForm'=>'FormPage04']);
                }catch (Exception $e){
                    $transaction->rollBack();
                    return $e->getMessage();
                }
            }
        } else if($imagesType=='DescImages'){
            $GoodsDescImages = GoodsDescImages::findOne($id);
            $goods_id  = $GoodsDescImages->goods_id;
            if (!@unlink(Yii::$app->basePath.$GoodsDescImages->goods_desc_image))
            {
                throw new Exception('图片文件删除失败');
            }
            $GoodsDescImages->delete();
            return $this->redirect(['updatepage','id'=>$goods_id,'whiceForm'=>'FormPage05']);
        }
    }

    /**
     * 选中更新页面
     *
     * Updates an existing Goods model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdatepage($id)
    {
        $model = $this->findModel($id);
        //选中显示页面
        $FormPage = isset($_GET['whiceForm'])?$_GET['whiceForm']:'FormPage01';
        //商品处理管理页面显示数据
        $GoodsGallImages = GoodsGallImages::find()->where(['goods_id'=>$id])->orderBy(['sort_number'=>SORT_ASC])->asArray()->all();
        $GoodsDescImages = GoodsDescImages::find()->where(['goods_id'=>$id])->orderBy(['sort_number'=>SORT_ASC])->asArray()->all();

        return $this->render('update', [
            'model' => $model,
            'GoodsGallImages'=>$GoodsGallImages,
            'GoodsDescImages'=>$GoodsDescImages,
            'FormPage'=>$FormPage
        ]);

    }

    /**
     * 选中更新页面
     *
     * Updates an existing Goods model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdateimagesdeal($id)
    {
        $model = $this->findModel($id);
        //选中显示页面
        $FormPage = isset($_GET['whiceForm'])?$_GET['whiceForm']:'FormPage01';
        //商品处理管理页面显示数据
        $GoodsGallImages = GoodsGallImages::find()->where(['goods_id'=>$id])->orderBy(['sort_number'=>SORT_ASC])->asArray()->all();
        $GoodsDescImages = GoodsDescImages::find()->where(['goods_id'=>$id])->orderBy(['sort_number'=>SORT_ASC])->asArray()->all();

        //
        $connection = Yii::$app->db;
        $transaction = $connection->beginTransaction();
        try{
            Goods::SortingImages($id);
            $transaction->commit();
            return $this->render('update', [
                'model' => $model,
                'GoodsGallImages'=>$GoodsGallImages,
                'GoodsDescImages'=>$GoodsDescImages,
                'FormPage'=>$FormPage
            ]);
        }catch (Exception $e){
            $transaction->rollBack();
            return $e->getMessage();
        }
    }

    /**
     * 整理图片数据
     *
     * @param $goods_id
     * @return string
     */
    public function actionSortingimage($goods_id)
    {
        //
        $connection = Yii::$app->db;
        $transaction = $connection->beginTransaction();
        try{
            Goods::SortingImages($goods_id);
            $transaction->commit();
            return json_encode([true,'']);
        }catch (Exception $e){
            $transaction->rollBack();
            return $e->getMessage();
        }
    }

    /**
     * 根据属性分类获取所有属性以及对应属性值
     *
     *
     * @return string
     */
    public function actionAttriall()
    {
        $post = Yii::$app->request->post();
        $ArbByArc = Goods::getArbByArcandgoods($post['attr_cat_id'],$post['goods_id']);
        return json_encode([true,$ArbByArc]);
    }

    public function actionSortdesc()
    {
//        $id = '0d0d6280-057d-11e8-b595-7da5fc148698';
        $GoodsDescImages = GoodsDescImages::find()->where(['type'=>1])->orderBy(['sort_number'=>SORT_ASC])->asArray()->all();

        return $this->render('sort', [
            'GoodsDescImages'=>$GoodsDescImages
        ]);
    }

//    /**
//     * 商品ID图上传xxxxxxxxxxxxxxxxxxxx
//     * @param $goods_id
//     * @return bool|string
//     */
//    public function uploadGoodsImages($goods_id)
//    {
//        $baseUrl = Yii::$app->basePath;
//        $webUrlBaseOnApp= '/web/images/goods/GoodsImages/'.$goods_id.'/';
//        $baseImages = $baseUrl.$webUrlBaseOnApp;
//        is_dir($baseImages) OR mkdir($baseImages, 0777, true);
//        $tmp_image = $_FILES['Goods']['tmp_name']['goods_image'];
//
//        $imageName = time().'-'.rand(100,10000).'png';
//        $objImage = $baseImages.$imageName;
//
//        if(move_uploaded_file($tmp_image,$objImage)){
//            return $webUrlBaseOnApp.$imageName;
//        }else{
//            return '';
//        }
//    }
}
